package self.zhangkang.android

import android.content.Context
import android.net.ConnectivityManager
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private lateinit var mConnectivityManager: ConnectivityManager


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mConnectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mConnectivityManager.registerDefaultNetworkCallback(object :
                    ConnectivityManager.NetworkCallback() {

                })
            }
        }
    }

    fun getNetwork(view: View) {
        network_tips.text = getTheLatestNetworkStatus()
    }


    fun getTheLatestNetworkStatus(): String {
        val activeNetworkInfo = mConnectivityManager.activeNetworkInfo
        return if (activeNetworkInfo?.isAvailable == true) {
            when (activeNetworkInfo.type) {
                ConnectivityManager.TYPE_WIFI -> {
                    "当前使用WIF"
                }
                ConnectivityManager.TYPE_MOBILE -> {
                    "当前使用4G"
                }
                else -> {
                    "当前网络可用"
                }
            }
        } else {
            "当前网络不可用"
        }
    }

}
